<?php
	session_start();
	include('../includes/db_connect.php');
	require_once('../core_lib/core_functions.php');
	error_reporting(0);
	function input_validation ($data, $charset = 'UTF-8') {
		if (is_array ($data)) {
			foreach ($data as $key => $value) {
				$data[$key] = input_validation ($value);
			}
		}
		else {
			$data = htmlentities (trim ($data), ENT_QUOTES, $charset);
		}
		return $data;
	}
	if (isset($_POST['user']) && isset($_POST['password'])) {	
		$raw_user = sanitize($_POST['user']);
		$raw_pass = sanitize($_POST['password']);
		$user = input_validation($raw_user);
		$pass = input_validation($raw_pass);
		if($_POST['type'] == 'admin') {		
			$query = "SELECT * 
											FROM user 
											WHERE user_name = '".$user."' 
											AND type_id = 2";
			$location = "../admin/admin.php";
		}else{
			$query = "SELECT * 
										 FROM user 
										 WHERE user_name = '".$user."'";
			$location = "../admin.php";
		}	
		$result = mysql_query($query);
		if($row = mysql_fetch_array($result)) {
				$this_user 										= $row["user_name"];
				$user_location 						= $row["location_id"];
				$salt 														= $row["salt"];
				$secure_password 					= $row["password"];
				$password 										= md5($salt.md5($pass));			
				if(strcmp($password, $secure_password)==0) {
						//Update user and set last login
						$todayMysql = date("Y-m-d H:i:s", mktime(date("H"),date("i"),date("s"),date("m"), date("d"), date("Y")));
						$update = "UPDATE user 
														 SET last_login = '".$todayMysql."' 
														 WHERE id = ".$row['id'];
						mysql_query($update);
						//Add login row to db for this user
						$ip=$_SERVER['REMOTE_ADDR'];
						$insert = "INSERT INTO user_history 
														 VALUES(NULL,".$row['id'].", 1, '".$ip."', '".$todayMysql."')";
						mysql_query($insert);
						//user tokens for valid login
						$_SESSION['logged_in'] 	= $_POST['user'];
						$_SESSION['user_id'] 			= $row['id'];
						$_SESSION['location'] 		= $user_location;
						//debug this shit
						//echo "<h1>".$_SESSION['logged_in']."</h1>";
						//echo "<h1>".$_SESSION['user_id']."</h1>";
						header('Location: '.$location);
						exit;
				}
				//echo "secure password: ".$secure_password."<br/>";
				//echo "password: ".$password."<br/>";
			}
	}
	header("Location: ../index.php?Status=Invalid Login");
	exit;
?>